// ~ CopyRight © 2012 USTC SINOVATE  SOFTWARE CO.LTD All Rights Reserved.
package com.cmcc.zysoft.sysmanage.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

//import com.cmcc.zysoft.infocollection.model.AdcProvisioningIct;
import com.cmcc.zysoft.infocollection.model.Company;
import com.cmcc.zysoft.sysmanage.dao.CompanyDao;
import com.cmcc.zysoft.sysmanage.dao.DepartmentDao;
import com.starit.common.dao.hibernate.HibernateBaseDao;
import com.starit.common.dao.service.BaseServiceImpl;

/**
 * @author li.menghua
 * @date 2012-11-28 下午3:54:21
 */
@Service
public class CompanyService extends BaseServiceImpl<Company, String>{
	
	/**
	 * 属性名称：_logger 类型：Logger
	 */
	private static Logger _logger = LoggerFactory.getLogger(CompanyService.class);
	
	/**
	 * 属性名称：companyDao 类型：CompanyDao
	 */
	@Resource
	private CompanyDao companyDao;
	
	/**
	 * 属性名称：departmentDao 类型：DepartmentDao
	 */
	@Resource
	private DepartmentDao departmentDao;
	
	@Resource
	private DepartmentService departmentService;
	
	@Value("${upload.file.path}")
	private String path;
	
	@Override
	public HibernateBaseDao<Company, String>getHibernateBaseDao(){
		return this.companyDao;
	}
	
	/**
	 * 更新公司信息
	 * @return 
	 */
	public void updateCompany(Company company){
		this.companyDao.addCompany(company);
	}
	
	/**
	 * 获取父企业列表
	 * @return 
	 */
	public List<Map<String, Object>> getCompanyTree(String companyId){
		List<Map<String, Object>> companyList = this.companyDao.getCompanyTree("0",companyId);
		return getSubComp(companyList,companyId);
	}
	
	/**
	 * 递归获取子企业列表
	 * @return 
	 */
	public List<Map<String, Object>> getSubComp(List<Map<String, Object>> companyList,String companyId){
		for(Map<String, Object> map : companyList){
			String haveChildCompany = map.get("have_child_company").toString();
			if("Y".equals(haveChildCompany)){
				String parentCompanyId = map.get("company_id").toString();
				List<Map<String, Object>> ChildList = this.companyDao.getCompanyTree(parentCompanyId,companyId);
				getSubComp(ChildList,companyId);
				map.put("children", ChildList);
				map.put("state", "closed");
			}else{
				map.put("state", "open");
			}
		}
		return companyList;
	}
	
	/**
	 * 通过公司Id获取公司实体
	 * @param companyId
	 * @return 
	 */
	public Company update(String companyId){
		return companyDao.get(companyId);
	}
	
	/**
	 * 增加企业
	 * @param  comp
	 * @return companyId
	 */
	public String addCompany(Company comp,HttpServletRequest request,MultipartFile photoFile) {
//		if(!"0".equals(comp.getParentCompanyId())){
//			Company father_comp = companyDao.get(comp.getParentCompanyId());
//			father_comp.setHaveChildCompany("Y");
//			companyDao.update(father_comp);
//		}
		if(photoFile.getSize() == 0){
			comp.setIndexLogo("");
		} else {
			String logo = this.uploadPhoto(request, photoFile);
			if(logo=="ERROR PHOTO"){
				return logo;
			}else{
				comp.setIndexLogo(this.uploadPhoto(request, photoFile));
			}
		}
		if(this.checkCompanyCode(comp.getCompanyCode())>0){
			return "companyCode error";
		}
		comp.setHaveChildCompany("N");
		comp.setDelFlag("0");
		comp.setParentCompanyId("0");
		String companyId = this.companyDao.save(comp);
		if(StringUtils.hasText(companyId)){
			_logger.debug("添加企业成功");
			return "SUCCESS";
		}else{
			_logger.debug("添加企业失败");
			return "ERROR";
		}
	}
	
	/**
	 * 修改企业信息
	 * @param  comp
	 * @return 
	 */
	public String updateCompany(Company comp,HttpServletRequest request,MultipartFile photoFile){
//		if(!"0".equals(comp.getParentCompanyId())){
//			Company father_comp = companyDao.get(comp.getParentCompanyId());
//			father_comp.setHaveChildCompany("Y");
//			companyDao.update(father_comp); //修改企业时，若选择的上级公司不为"无",则将所选择的上级公司是否有子公司状态改为"Y"
//		}
		Company new_comp=companyDao.get(comp.getCompanyId());
//		if(!new_comp.getParentCompanyId().equals(comp.getParentCompanyId()) && !"0".equals(new_comp.getParentCompanyId())){
//			List<Company> list = this.findByNamedParam(new String[]{"parentCompanyId","delFlag"}, new Object[]{new_comp.getParentCompanyId(), "0"});
//			if(list.size()==1){
//				Company father_comp_new = companyDao.get(new_comp.getParentCompanyId());
//				father_comp_new.setHaveChildCompany("N");
//				companyDao.update(father_comp_new); //修改企业时,如果修改了上级公司,且之前的父公司下只有这一个子公司，则将之前的父公司的是否有子公司状态改为"N"
//			}
//		}
		if(photoFile.getSize() == 0){
			new_comp.setIndexLogo(comp.getIndexLogo());
		} else {
			String logo = this.uploadPhoto(request, photoFile);
			if(logo=="ERROR PHOTO"){
				return logo;
			}else{
				new_comp.setIndexLogo(this.uploadPhoto(request, photoFile));
			}
		}
		new_comp.setCompanyName(comp.getCompanyName());
		new_comp.setCompanyAddress(comp.getCompanyAddress());
		new_comp.setContactMan(comp.getContactMan());
		new_comp.setTelephone(comp.getTelephone());
		new_comp.setFax(comp.getFax());
		new_comp.setLoginUrl(comp.getLoginUrl());
		companyDao.update(new_comp);
		_logger.debug("修改企业信息成功");
		return "SUCCESS";
	}
	
	/**
	 * 删除企业,若删除该企业后，上级企业下面已无任何子企业,则将上级企业改为无子企业状态
	 * @param companyId
	 */
	public void deleteCompany(String companyId){
		Company comp = companyDao.get(companyId);
		comp.setDelFlag("1");
		this.companyDao.update(comp);
		if(!comp.getParentCompanyId().equals("0")){
			List<Company> list = this.findByNamedParam(new String[]{"parentCompanyId","delFlag"}, new Object[]{comp.getParentCompanyId(), "0"});
			if(list.size()==0){
				Company father_comp_new = this.companyDao.get(comp.getParentCompanyId());
				father_comp_new.setHaveChildCompany("N");
				this.companyDao.update(father_comp_new);
			}
		}
	}
	
	/**
	 * combortree 获取公司树
	 * @author yandou
	 * @param companyId 
	 * @return
	 */
	public List<Map<String, Object>> companyTree(String companyId) {
		// companyId 只能对该公司以下公司或部门的人员设置权限
		List<Map<String, Object>> list = this.companyDao.companyTree(companyId);
		return getChildComp(list);
	}
	
	/**
	 * 获取子公司，递归，
	 * @author yandou
	 * @param list
	 * @return
	 */
	public List<Map<String, Object>> getChildComp(List<Map<String, Object>> list){
		for(Map<String,Object> map : list){
			String hasChildCom = map.get("haveChildCom").toString();
			map.put("iconCls", "company");//添加图标
			if("Y".equals(hasChildCom)){//存在子公司
				String companyId = map.get("id").toString();
				List<Map<String, Object>> childList = this.companyDao.companyTree(companyId);
				getChildComp(childList);
				map.put("state", "closed");
				map.put("children", childList);
			}else{
				map.put("state", "open");
			}
		}
		return list;
	}
	
	/**
	 * 上传图片
	 * @author yandou
	 * @return
	 */
	public String uploadPhoto(HttpServletRequest request,MultipartFile photoFile) {
		//在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹  
        String filename = photoFile.getOriginalFilename();
        String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase(); 
        try {
        	if(extName.trim().equals(".gif")||extName.trim().equals(".jpg")||extName.trim().equals(".jpeg")||extName.trim().equals(".png")||extName.trim().equals(".bmp")){
    	        String lastFileName = System.currentTimeMillis()+extName;
//    	        String path = "/resources/image/upload/companyLogo/";
//    	        String fileFullPath = request.getServletContext().getRealPath("")+path+lastFileName;
    	        //图片存储的相对路径   
    	        String fileFullPath = path+File.separator+"company_"+lastFileName;
    			FileCopyUtils.copy(photoFile.getBytes(),new File(fileFullPath));  
    			return "company_"+lastFileName;
            }else{
            	return "ERROR PHOTO";
            }
		} catch (Exception e) {
			return "ERROR";
		}
	}

	/**
	 * 立即定位树显示
	 * @param id
	 * @return
	 */
	public List<Map<String, Object>> comsForImmeLocat(String id) {
		List<Map<String, Object>> coms =  this.companyDao.companyTree(id);
		for(Map<String,Object> map : coms){
			String companyId = map.get("id").toString();
			map.put("id", "c_"+companyId);
			map.put("iconCls", "company");
			List<Map<String, Object>> deptList = this.departmentDao.departmentTree("0", companyId);
			if("Y".equals(map.get("haveChildCom").toString())){
				map.put("state", "closed");
			}else{
				if(deptList.isEmpty()){
					map.put("state", "open");
				}else{
					map.put("state", "closed");
				}
			}
		}
		return coms;
	}
	
	/**
	 * 根据员工ID获取其所属的所有公司（子公司及其父公司）
	 * @author yuan.fengjian@ustcinfo.com
	 * @param employeeId
	 */
	public List<Map<String,Object>> getParentComs8EmpId(String employeeId) {
		String companyId = this.companyDao.getComId8EmpId(employeeId);
		List<Map<String, Object>> parentDept = this.departmentService.getParentDept8EmpId(employeeId);
		List<Map<String, Object>> parentComs = this.getParentComs(companyId, parentDept);
		return parentComs;
	}
	
	/**
	 * 获取其所属的所有公司、部门、子部门和员工
	 * @author yuan.fengjian@ustcinfo.com
	 * @param companyId
	 * @param parentDept
	 */
	public List<Map<String, Object>> getParentComs(String companyId, List<Map<String, Object>> parentDept) {
		List<Map<String, Object>> parentComs = this.companyDao.getCom8ComId(companyId);
		parentComs.get(0).put("id", "c_"+parentComs.get(0).get("id").toString());
		parentComs.get(0).put("iconCls", "company");
		parentComs.get(0).put("state", "open");
		parentComs.get(0).put("children", parentDept);
		String parentComId = parentComs.get(0).get("parent_company_id").toString();
		if(!"0".equals(parentComId)) {
			this.getParentComs(parentComId, parentComs);
		}
		return parentComs;
	}
	
	/**
	 * 查询公司
	 * @param deptName
	 * @return
	 */
	public List<Map<String, Object>> searchComp(String companyName){
		Map<String, Object> map = null;
		List<Map<String, Object>> list = this.companyDao.searchComp(companyName);
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		if(null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++) {
				map = list.get(i);
				if(!"0".equals(map.get("parent_company_id").toString())){
					parentList.addAll(searchParent(map.get("parent_company_id").toString()));
				}
			}
			list.addAll(parentList);
		}
		return list;
	}
	
	/**
	 * 查询时，获取查询到的公司的上级公司
	 * @param parentCompanyId
	 * @return
	 */
	public List<Map<String, Object>> searchParent(String parentCompanyId){
		List<Map<String, Object>> parentList = this.companyDao.searchCompByCompId(parentCompanyId);
		Map<String,Object> parentMap = parentList.get(0);
		if(!"0".equals(parentMap.get("parent_company_id").toString())){
			parentList.addAll(searchParent(parentMap.get("parent_company_id").toString()));
		}
		return parentList;
	}
	
	/**
	 * 查找相同企业编码的数量
	 * @param companyCode
	 * @return
	 */
	public int checkCompanyCode(String companyCode){
		List<Company> list = this.findByNamedParam("companyCode",companyCode);
		return list.size();
	}
	
	/**
	 * 根据登录地址获取公司
	 * @param loginUrl 登录地址pattern 
	 * <p>e.g:http://localhost:8181/cmcc,响应的pattern是cmcc</p>
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Company getCompanyByUrl(String loginUrl){
		String hql = "from Company as c where c.loginUrl = ? and c.delFlag='0'";
		List<Company> companies = this.companyDao.findByHQL(hql, loginUrl);
		return companies.isEmpty()?null:companies.get(0);
	}
	
	/**
	 * 公司部门树(员工管理,基础数据模块,销售管理模块)
	 * 先找到公司
	 * @param companyId
	 * @return
	 */
	public List<Map<String, Object>> getCompanyTreeHql(String companyId){
		return this.companyDao.getCompanyTreeHql(companyId);
	}
	
	/**
	 * 根据公司编码获取公司信息
	 * @param companyCode
	 * @return 返回类型：Company
	 */
	public Company getCompanyByCode(String companyCode){
		List<Company> companies = this.companyDao.findByNamedParam("companyCode", companyCode);
		if(!companies.isEmpty()){
			return companies.get(0);
		}
		return null;
	}
	
	/**
	 * 添加公司
	 * @param company
	 * @return 返回类型：String
	 */
	public String addCompany(Company company){
		return this.companyDao.addCompany(company);
	}
	
	/**
	 * 判断公司类型
	 * @author yandou
	 * @param companyId
	 * @return
	 */
	/*public boolean checkCompanyType(String companyId) {
		boolean flag = false;
		Company company = this.getEntity(companyId);
		if(company != null){
			String companyCode = company.getCompanyCode();
			List<AdcProvisioningIct> adcProvisioningIcts = this.adcProvisioningIctDao.findByNamedParam("ecCode",companyCode);
			if(!adcProvisioningIcts.isEmpty()){
				AdcProvisioningIct adcProvisioningIct = adcProvisioningIcts.get(0);
				String serviceName = adcProvisioningIct.getServiceName();
				if(serviceName.indexOf("外勤") != -1){
					flag = true;
				};
			}
		}
		return flag;
	}*/

	/**
	 * 从菜单中获取公司信息
	 * @return
	 */
	public List<Map<String, Object>> getSyschroMenuCompany() {
		return this.companyDao.getSyschroMenuCompany();
	}
	
}
